package com.cxx.autoconfigure.web;

import com.cxx.autoconfigure.config.WebProperties;
import com.cxx.autoconfigure.constant.Constants;
import com.cxx.autoconfigure.interceptor.AuditInterceptor;
import com.cxx.autoconfigure.serializer.MyBeanSerializerModifier;
import com.fasterxml.jackson.databind.ser.SerializerFactory;
import io.swagger.v3.core.util.PrimitiveType;
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.info.Info;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.annotation.Order;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 自动配置 实现InitializingBean, WebMvcConfigurer
 * 实现EnvironmentAware是为了获取当前的Spring的Environment对象
 * 该对象提供了对 Spring 配置环境的访问，能够读取配置属性、系统环境变量、JVM 参数、以及其他与环境相关的信息
 * <p>
 * SpringBoot MVC总体执行顺序：
 * 1. 进入Tomcat容器
 * 2. 进入Filter过滤器
 * 3. 进入Servlet容器
 * 4. 进入Interceptor拦截器
 * 5. 进入Controller控制器
 * 6. 进入AOP
 */
@Configuration()
@Import({DefaultExceptionAdvice.class, JacksonModuleRegister.class, AuditBodyAdvice.class, WebProperties.class})
@OpenAPIDefinition(info = @Info(title = "${spring.application.name}", version = "${spring.application.version}"))
public class ServerAutoConfiguration implements InitializingBean, WebMvcConfigurer {
    @Resource
    private WebProperties webProperties;

    @Override
    public void afterPropertiesSet() throws Exception {
        PrimitiveType.enablePartialTime();
    }

    /**
     * 配置格式化器和转换器 需要实现 WebMvcConfigurer 接口
     * @param registry 注册器
     */
    @Override
    public void addFormatters(FormatterRegistry registry) {
        DateTimeFormatterRegistrar dateTimeRegistrar = new DateTimeFormatterRegistrar();
        dateTimeRegistrar.setDateTimeFormatter(DateTimeFormatter.ofPattern(Constants.DATE_TIME_PATTERN));
        dateTimeRegistrar.setDateFormatter(DateTimeFormatter.ofPattern(Constants.DATE_PATTERN));
        dateTimeRegistrar.setTimeFormatter(DateTimeFormatter.ofPattern(Constants.TIME_PATTERN));
        dateTimeRegistrar.registerFormatters(registry);
    }

    /**
     * 扩展消息转换器
     * @param converters 转换器
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(jacksonHttpMessageConverter());
    }

    @Bean
    public MappingJackson2HttpMessageConverter jacksonHttpMessageConverter() {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        // 增加自定义序列化处理
        SerializerFactory serializerFactory = converter.getObjectMapper()
                .getSerializerFactory().withSerializerModifier(new MyBeanSerializerModifier());

        converter.getObjectMapper().setSerializerFactory(serializerFactory);

        return converter;
    }

    /**
     * 注册拦截器  需要实现 WebMvcConfigurer 接口
     * @param registry 注册器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // registry.addInterceptor(new SecurityInterceptor());
        registry.addInterceptor(new AuditInterceptor(webProperties.getBasePackage()));
        // 注册Sa-Token拦截器 登录校验
//        registry.addInterceptor(new SaInterceptor(handle -> StpUtil.checkLogin()))
//                .excludePathPatterns("/error", "/swagger-ui/**", "/swagger-resources/**", "/v3/api-docs/**")
//                .excludePathPatterns("/doc.html", "/webjars/**");
    }

    /**
     * 配置CORS跨越 需要实现 WebMvcConfigurer 接口
     * @return 过滤器
     */
    @Bean
    @Order(-128)
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        // 允许所有来源
        config.addAllowedOrigin("*");
        // 允许所有请求头
        config.addAllowedHeader("*");
        // 允许所有请求方法
        config.addAllowedMethod("*");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}
